from paho import mqtt
import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
import time
import json
from common import mqttConfiguration
from common.contactStr import sqlContact, mqttMessageContact
from common.mysqlUtil import exc_sql

'''
* Mqtt client 工具类
*
* @author madaoli
* @version 2020-01-26 13:25
*/
'''
client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
mqttClient = mqtt.Client(client_id, transport='tcp')
'''
* 初始化Mqtt客户端，默认订阅配置的Topic
*
* @param mqttConfiguration mqtt配置
* @return 返回已经完成连接的MqttClient
'''


# 连接服务器，mqttConfiguration 对象下需要初始化成员变量的值
def on_mqtt_connect(MQTTconf):
    mqttClient.username_pw_set(MQTTconf.get("userName"), MQTTconf.get("passWord"))
    mqttClient.connect(MQTTconf.get("url"), 1883, 60)
    mqttClient.loop_start()
    # print(MQTTconf)
    print("connect success!!")


# 使用mqttClient发布消息
def publishMqttData(MQTTconf, data):
    mqttClient.publish(MQTTconf.get("topic"), data, qos=1)
    # print(data)
    print("publish success!!")


# 使用publish single发布消息，可以不调用connect
def publishMqttData1(MQTTconf, data):
    publish.single(MQTTconf.get("topic"), data, qos=1, hostname=MQTTconf.get("url"), port=1883, client_id=client_id,
                   auth={'username': MQTTconf.get("userName"), 'password': MQTTconf.get("passWord")})
    print("publish success!!")

# if __name__ == '__main__':
#     mqttConfiguration= mqttConfiguration
# mqttConfiguration.url = "10.10.15.133"
# mqttConfiguration.topic="/SDSC/PUT" #/SDSC/PUT
# mqttConfiguration.userName="wpg"
# mqttConfiguration.passWord="Wpg$_$EmQxZ0iG"
# mqttConfiguration.url = "119.3.24.173"
# mqttConfiguration.topic="/SDSC/PUT" #/SDSC/PUT" #/SDSC/PUT
# mqttConfiguration.userName="wpg"
# mqttConfiguration.passWord="admin!@#"
# deviceID="16040140"
# point_values={"A133":"1","No1OT25":"0","No2OT25":"1","No3OT25":"0","No4OT25":"1"}
# sqldata=sqlContact(deviceID,point_values)
# mqttdata=mqttMessageContact(deviceID,point_values)
# print(sqldata)
# print(json.dumps(mqttdata))
# on_mqtt_connect(mqttConfiguration)
# publishMqttData(mqttConfiguration,str(mqttdata))
# exc_sql(sqldata,"db1")
